import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    id: '',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    companyId: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_DEPT: (state, companyId) => {
    state.companyId = companyId
  }
}

const actions = {
  // // 用户注册
  // register({ commit }, userInfo) {
  //   return new Promise((resolve, reject) => {
  //     register(userInfo).then(res => {
  //       console.log(res)
  //       commit('SET_TOKEN', res.data)
  //       setToken(res.data)
  //       commit('SET_NAME', res.data.userid)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  // user 登录
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      const { userid, userPwd } = userInfo
      login(userid, userPwd).then(res => {
        console.log(res)
        commit('SET_TOKEN', res.data)
        setToken(res.data)
        commit('SET_NAME', res.data.userName)
        commit('SET_ID', res.data.id)
        commit('SET_DEPT', res.data.companyId)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response

        // if (!data) {
        //   reject('登录已过期，请重新登陆')
        // }

        commit('SET_DEPT', data.companyId)
        commit('SET_NAME', data.userName)
        commit('SET_ID', data.id)
        // commit('SET_AVATAR', avatar) // 用户头像
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  setDept({ commit }, companyId) {
    commit('SET_DEPT', companyId)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

